import * as XLSX from "xlsx";
// 前端导出表格的方法
export function createTables( Header, content, tableName ) {
    let table = document.createElement( "table" ); //创建table
    let thead = document.createElement( "thead" ); //thead
    let tbody = document.createElement( "tbody" ); //thead
    let tr = document.createElement( "tr" ); //创建tr
    table.appendChild( thead );
    table.appendChild( tbody );
    thead.appendChild( tr );
    // 创建表头
    Header.forEach( ( item ) => {
        // console.log('@000', item);
        let th = document.createElement( "th" );
        th.innerHTML = item.title;
        tr.appendChild( th );
    } );
    // 添加内容
    content.forEach( ( item ) => {
        let tr = document.createElement( "tr" ); //创建tr
        tbody.appendChild( tr );
        Header.forEach( ( item2 ) => {
            let td = document.createElement( "td" );
            let itemString = Object.entries( item );
            for ( let item3 of itemString ) {
                if ( item2.key === item3[ 0 ] ) {
                    td.innerHTML = item3[ 1 ];
                }
            }
            tr.appendChild( td );
        } );
    } );
    //导出
    // 1.table 转 sheet 页
    let worksheet = XLSX.utils.table_to_sheet( table );
    // console.log('@worksheet', worksheet);

    // 2.新建工作簿
    let workbook = XLSX.utils.book_new();
    // console.log('@workbook', workbook);
    // 将表格内容变成文本 (转了后就不能设置列宽了)
    let xlsxParam = { raw: true }; // 将表格数据设置为文本格式
    workbook = XLSX.utils.table_to_book( table, xlsxParam );

    // 3.设置列宽
    let wscols = [
        { wch: 20 },
        { wch: 40 },
        { wch: 40 },
        { wch: 40 },
        { wch: 40 },
        { wch: 40 },
        { wch: 60 },
        { wch: 60 },
    ];
    // let wscols = [...props.wscolsList];

    // workbook.SheetNames[0]获取到到是文件里的到第一个表格
    worksheet[ "!cols" ] = wscols;
    let wsrows = [ { hpx: 20 } ]; // 每行固定高度px
    for ( let i = 0; i <= 5; i++ ) {
        wsrows.push( { hpx: 20 } );
    }
    worksheet[ "!rows" ] = wsrows;
    // let xlsxParam = { raw: true }; // 将表格数据设置为文本格式
    // 4.工作簿 调用 table_to_book() 方法   把表格 和 xlsx 的参数传进去
    // workbook = XLSX.utils.table_to_book(table, xlsxParam);
    XLSX.utils.book_append_sheet( workbook, worksheet, "sheet" );
    try {
        // 5.输出表格
        XLSX.writeFile( workbook, `${tableName || '表格名称'}.xlsx` );
    } catch ( e ) {
        console.log( e, workbook );
    }
}